<template>
    <div>
        <van-field
                readonly
                v-model="selected"
                :name="name"
                :required="required"
                :label="label"
                :placeholder="placeholder"
                :border="border"
                :rules="selectRule"
                @click="openSelection">
        </van-field>

        <div :id="containerId" style="width: 100%" class="search-select-ty"></div>
        <van-popup v-model="show" bind:close="onClose" :get-container="getContainer">
            <van-nav-bar
                    title="多选"
                    @click-left="onClose"
                    @click-right="saveSelected"
                    left-arrow
                    left-text="返回"
                    right-text="确定">
            </van-nav-bar>

            <van-cell-group>
                <van-field
                        clearable
                        v-model="keyword"
                        right-icon="search"
                        placeholder="请输入关键字搜索"
                        @click-right-icon="onRefresh"
                        @input="searchByKeyword">
                </van-field>
            </van-cell-group>

            <van-pull-refresh v-model="pullLoading" @refresh="onRefresh">
                <van-radio-group v-model="selectedValue">
                    <van-list
                            v-model="listLoading"
                            :finished="listFinished"
                            :finished-text="finishedText"
                            :error.sync="listError"
                            error-text="请求失败，点击重新加载"
                            @load="onLoad()">

                        <van-cell v-for="(item,index) in selections" :key="index">
                            <van-radio slot="icon" :name="item.value"/>
                            <span slot="title" style="margin-left: 5px;">{{ item.text }}</span>
                        </van-cell>

                    </van-list>
                </van-radio-group>
            </van-pull-refresh>
        </van-popup>
    </div>
</template>

<script>
  //下拉多选只支持 字典 不支持表

  import debounce from 'lodash/debounce';
  import { getAction } from "@/api";

  export default {
    name: "AppMultiSelect",
    props:{
      display:{
        type:String,
        default:'inline-block',
        required:false
      },
      placeholder:{
        type:String,
        default:'请选择',
        required:false
      },
      label:{
        type:String,
        default:'',
        required:false
      },
      value:{
        type:String,
        required:false
      },
      border:{
        type:Boolean,
        default:false,
        required:false
      },
      dictCode:{
        type:String,
        default:'',
        required:true
      },
      name:{
        type:String,
        default:'',
        required:false
      },
      required:{
        type:Boolean,
        default:false,
        required:false
      }

    },
    data(){
      this.searchByKeyword = debounce(this.searchByKeyword, 1000);//消抖
      return {
        show:false,
        containerId:'',
        selected:'',
        selectedValue:'',

        keyword:'',
        pageSize:10,
        pageNo:1,

        pullLoading: false,
        listLoading: false,
        listFinished:false,
        finishedText:'没有更多了',
        listError:false,

        selections:[],

      }
    },
    watch:{
      value:{
        immediate:true,
        handler(val){
          if(!val){
            this.selected = ''
            this.selectedValue = ''
          }else{
            this.loadItemByValue()
          }
        }
      },
      dictCode:{
        immediate:true,
        handler(){
          this.initContainerId();
          this.onRefresh()
        }
      }

    },
    computed:{
      selectRule(){
        if(this.required===true){
          return [{ required: true, message: `请选择${this.label}`}]
        }else{
          return [];
        }
      }
    },
    methods:{
      openSelection(){
        this.show = true
      },
      initContainerId(){
        this.containerId = 'msty'+new Date().getTime();
      },
      getContainer(){
        return document.getElementById(this.containerId)
      },
      onClose(){
        this.show = false;
      },
      searchByKeyword(){
        this.onRefresh()
      },

      saveSelected(){
        if(!this.selectedValue || this.selectedValue.length==0){
          this.$toast.fail('请选择一项!');
          return false;
        }
        this.initTextByCode(this.selectedValue);
        this.$emit('change',this.selectedValue)
        this.onClose();
      },
      initTextByCode(value){
        this.selections.map(item=>{
          if(item.value===value){
            this.selected = item.title
          }
        });
      },

      loadItemByValue(){
        let arr = this.dictCode.split(',');
        let param = {
          table:arr[0],
          text:arr[1],
          code:arr[2],
          codeValue:this.value
        };
        getAction('/sys/dict/queryTableData', param).then(res=>{
          if(res.success){
            let record = res.result[0];
            this.selected = record.text;
            this.selectedValue = record.value;
          }
        })
      },
      onRefresh(){
        this.pageNo = 1;
        this.onLoad();
      },

      onLoad(){
        this.listLoading = true;
        //dictTable,dictText,dictCode
        let arr = this.dictCode.split(',')
        let param = {
          table:arr[0],
          text:arr[1],
          code:arr[2],
          pageSize:this.pageSize,
          pageNo:this.pageNo,
          keyword:this.keyword
        };
        if(this.pageNo===1){
          this.selections = []
        }
        getAction('/sys/dict/queryTableData', param).then(res=>{
          this.listLoading = false;
          this.pullLoading = false;
          if(res.success){
            // this.$toast.success("加载完成");
            this.pageNo++;
            let arr = res.result;
            for(let item of arr){
              this.selections.push(item)
            }
            if(!arr || arr.length<this.pageSize){
              console.log("加载完成!")
              this.listFinished = true;
            }
          }else{
            this.error = true;
          }

        }).catch(e=>{
          console.log("请求错误",e)
          this.error = true;
        })
      },
    },
    model: {
      prop: 'value',
      event: 'change'
    }
  }
</script>

<style>
.search-select-ty .van-popup{width:100%;height: 100%;}
</style>